<template>
  <div class="redistribution-container">
    <!-- 栅格 输入框 和按钮 -->
    <el-row class="filterCondition">
      <el-form label-width="82px" label-position="right" :model="formLabelAlign">
        <el-form-item  label="回访时间" >
          <el-radio-group v-model="visitDayTypeLinShi" @change="agreeChange">
            <el-radio :label="1" >不限</el-radio>
            <el-radio :label="2">上月</el-radio>
            <el-radio :label="3">昨日</el-radio>
            <el-radio :label="4">今日</el-radio>
            <el-radio :label="5">最近7天</el-radio>
            <el-radio :label="6">本月</el-radio>
          </el-radio-group>
        </el-form-item><br>
        <el-form-item label=" 客户" >
          <el-input v-model="formLabelAlign.keywords" placeholder="姓名/ID/手机号均可"></el-input>
        </el-form-item>
        <el-form-item label="星级">
          <el-select v-model="formLabelAlign.level" placeholder>
            <el-option label="所有" value=""></el-option>
            <el-option label="0星" value=0></el-option>
            <el-option label="1星" value=1></el-option>
            <el-option label="2星" value=2></el-option>
            <el-option label="2星+" value=3></el-option>
            <el-option label="3星" value=4></el-option>
            <el-option label="4星" value=5></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formLabelAlign.state" placeholder>
            <el-option label="所有" value=""></el-option>
            <el-option label="已受理" value="已受理"></el-option>
            <el-option label="未接通" value="未接通"></el-option>
            <el-option label="待跟进" value="待跟进"></el-option>
            <el-option label="资质不符" value="资质不符"></el-option>
            <el-option label="待签约" value="待签约"></el-option>
            <el-option label="已上门" value="已上门"></el-option>
            <el-option label="已签约" value="已签约"></el-option>
            <el-option label="已拒批" value="已拒批"></el-option>
            <el-option label="审核中" value="审核中"></el-option>
            <el-option label="已放款" value="已放款"></el-option>
            <el-option label="捣乱申请" value="捣乱申请"></el-option>
            <el-option label="重复申请" value="重复申请"></el-option>
            <el-option label="外地申请" value="外地申请"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formLabelAlign.content "></el-input>
        </el-form-item>
        <el-form-item label="备注条数">
          <el-input v-model="formLabelAlign.contentCount" type="number"></el-input>
        </el-form-item>
        <el-form-item prop="weiLianXiDays" label="未联系天数">
          <el-input v-model="formLabelAlign.weiLianXiDays" type="number" placeholder="仅支持阿拉伯数字"></el-input>
        </el-form-item>
        <el-form-item prop="timeType" label="时间">
          <el-select v-model="formLabelAlign.timeType" @change="hiddenTimeKind"  placeholder="分类">
            <el-option label="所有" value=""></el-option>
            <el-option
              v-for="item in kindtimeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-select v-model="formLabelAlign.dayType" id="time" @change="holderQuJian" placeholder="时间" :disabled="this.showTimeKind">
            <el-option
              v-for="item in timeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间区间" v-show="isShow">
          <div class="block" >
            <el-date-picker
              v-model="value1"
              type="daterange"
              format="yyyy/MM/dd"
              value-format="yyyy/MM/dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </div>
        </el-form-item>
        <el-button style="background-color:#c73e3a;color:#fff" :disabled="disTBN" @click="checkCus" class="check">查询</el-button>
        <el-button style="background-color:#008C5E;color:#fff" :disabled="disTBN" @click="addGGC" class="check">加入公共池</el-button>
      </el-form>
      <div id="unread">
        <span class="unread">待处理客户提醒：您有<span class="unreadNuM" @click="enterDetail('level0')">{{this.daiGenJinNum.level0Count}}</span>位0星客户超过6h未联系；<span class="unreadNuM" @click="enterDetail('level2')">{{this.daiGenJinNum.level2count}}</span>位2星及2星+客户超过6天未联系；<span class="unreadNuM" @click="enterDetail('level3')">{{this.daiGenJinNum.level3count}}</span>位3星及4星客户超过4天未联系,若不及时处理将被加入公共池</span>
      </div>
    </el-row>
    <!-- table -->
    <!-- <el-table  @selection-change="changeCus" :row-class-name="tableRowClassName" :data="tableData" style="width: 100%" stripe> -->
    <el-table  @selection-change="changeCus"  :data="tableData" v-loading="loading" style="width: 100%" stripe>
      <el-table-column type="selection" width="30" ></el-table-column>
      <el-table-column prop="id" label="ID" width="60" align="center"></el-table-column>
      <el-table-column  label="姓名" width="80" align="center">
        <template slot-scope="scope"><i v-show="scope.row.ShowStar" style="color:red" class="el-icon-star-on"></i><a  size="mini" @click="handleEdit(scope.$index, scope.row)">{{ scope.row.name}}</a></template>
      </el-table-column>
      <el-table-column  label="状态" width="80" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.state == '资质不符' " style='color:#C73E3A'>{{ scope.row.state}}</span>
          <span v-else-if=" scope.row.state == '已签约'||scope.row.state == '已上门'  || scope.row.state == '待签约'|| scope.row.state == '已放款'|| scope.row.state == '审核中'" style='color:#5BBD2B'>{{ scope.row.state}}</span>
          <span v-else-if="scope.row.state == '已受理' || scope.row.state == '未接通' || scope.row.state == '待跟进'" style='color:#3390ff'>{{ scope.row.state}}</span>
          <span v-else-if="scope.row.state == '捣乱申请' || scope.row.state == '外地申请'|| scope.row.state == '已拒批'|| scope.row.state == '重复申请'" style='color:#D7962F'>{{ scope.row.state}}</span>
          <span v-else style='color:grey'>{{ scope.row.state}}</span>
          </template>
      </el-table-column>
      <el-table-column  label="星级" width="50" align="center">
        <template slot-scope="scope">{{ scope.row.level| levelKind }}</template>
      </el-table-column>
      <el-table-column label="备注" sortable>
        <template slot-scope="scope">
          <p class="ell" v-for="(item,index) in scope.row.noteList" :key="index" v-if="index<3" v-bind:style="{'color': item.otherUser == 1 ? 'red':'#606266'}">&nbsp;<span v-bind:style="{'color': item.otherUser == 1 ? '#898989':'#898989'}">{{++index}}--{{item.createDate | formatTime }}--{{item.userName}}</span>--{{item.content}}</p>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="资质" width="200" align="center">
        <template slot-scope="scope"><apan>{{ scope.row.remarks | remarksPanKong}}</apan></template>
      </el-table-column>
      <el-table-column  label="时间" width="150" align="center">
        <template slot-scope="scope">
          <p class="ell">分配：{{ scope.row.distributionTime | formatTime }}</p>
          <p class="ell">再分配：{{ scope.row.zfpTime | formatTime }}</p>
          <p class="ell">回访：{{ scope.row.returnVisitTime | formatTime }}</p>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination  @size-change="handleSizeChange"  @current-change="handleCurrentChange"  :current-page="pageConfig.currentPage"  :page-sizes="[10, 20 ,50, 100]"  :page-size="pageConfig.pageSize"  layout="total, sizes, prev, pager, next, jumper"  :total="pageConfig.total">
    </el-pagination>
  </div>
</template>

<script>
// 导入时间戳
import moment from 'moment'
import { mapMutations } from 'vuex';
export default {
  name: "redistribution",
  // 数据
  data() {
    return {
      currentUser:{
        currentName:"",
        currentId:"",
        currentPhone:""
      },
      visitDayTypeLinShi:1,  //避免冲突 临时存储时间区间
      value1: "",//未分割的完整版时间区间
      isShow:false,//时间区间隐藏状态
      loading:true, 
      pageConfig:{//页码参数
        currentPage:1,//当前页
        pageSize:10,//当前单页数据条数
        total:0,//请求到的数据总条数
      },
      showTimeKind:true,
      kindtimeList:[
        { id: "beizhuTime", name: "备注时间" },
        { id: "fenpeiTime", name: "分配时间" },
      ],
      timeList: [
        { id: "", name: "不限" },
        { id: "today", name: "今日" },
        { id: "yestoday", name: "昨日" },
        { id: "sevenDay", name: "最近七天" },
        { id: "tomonth", name: "本月" },
        { id: "yesmonth", name: "上月" },
        { id: "customize", name: "自定义" },
      ],
      //客户筛选区域数据
      formLabelAlign: {
        keywords : "", 	//关键字
        level : "", 	//	星级
        state : "", 	//	状态
        content : "", 	//备注内容
        contentCount : "", 	//备注条数
        timeType: "", 	//时间类型
        dayType:"",
        weiLianXiDays:"", //未联系天数
        beginTime : "", 	//开始时间
        endTime : "",  //	结束时间
        pageSize : "", 	//分页大小
        currentPage : "", //	当前页码
        visitDayType:"", //	在跟进时间条件
      },
      disTBN : false,
      //待处理的客户数量
      daiGenJinNum:{
        level0Count:0,
        level3count:0,
        level2count:0
      },
      //加入公共池的客户id数组
      customerId:[],
      tableData: [],
      ReCusIdList:[] , //存储再分配客户id表的数组
    };
  },
  methods: {
    //表格各行变色的方法
    tableRowClassName({row, rowIndex}) {
      if(rowIndex%2==1){
        return 'warning-row';
      }else{
        return 'success-row';
      }
    },
    //获取客户 List的方法
    getCusList(){
      this.loading = true
      this.$axios
      .post(`/spider/customer/getAllCustomerList?userId=${this.currentUser.currentid}&searchType=true&keywords=${this.formLabelAlign.keywords}&visitDayType=${this.formLabelAlign.visitDayType}&weiLianXiDays=${this.formLabelAlign.weiLianXiDays}&level=${this.formLabelAlign.level}&state=${this.formLabelAlign.state}&content=${this.formLabelAlign.content}&contentCount=${this.formLabelAlign.contentCount}&timeType=${this.formLabelAlign.timeType}&dayType=${this.formLabelAlign.dayType}&beginTime=${this.formLabelAlign.beginTime}&endTime=${this.formLabelAlign.endTime}&currentPage=${this.pageConfig.currentPage}&pageSize=${this.pageConfig.pageSize}`)
      .then(res => {
        // console.log(res);
        if (res.data.messageModel.code == 0) {
          if (res.data.dataModel.total == 0) {
            this.$message('抱歉，没有找到符合搜索条件的客户');
            this.tableData = res.data.dataModel.list;
            this.pageConfig.total = res.data.dataModel.total;
            this.clearAllCheck();
            this.loading = false
            return false;
          }
          //判断客户再分配时间晚于备注时间的方法开始
          let DataList = res.data.dataModel.list
          for (let i = 0; i < DataList.length; i++) {
            if (DataList[i].zfpTime != ""&& DataList[i].lastNoteTime != "" && DataList[i].zfpTime != null&& DataList[i].lastNoteTime != null) {
              if (moment(DataList[i].zfpTime).valueOf() > moment(DataList[i].lastNoteTime).valueOf()) {
                DataList[i].ShowStar = true;
              }else{
                DataList[i].ShowStar = false;
              }
            }
            if (DataList[i].lastNoteTime == null || DataList[i].lastNoteTime == "null") {
              DataList[i].ShowStar = true;
            }
          }
          //判断客户再分配时间晚于备注时间的方法结束
          this.tableData = DataList;
          this.pageConfig.total = res.data.dataModel.total;
          //将获取的再分配客户ID表存入本地
          this.ReCusIdList = this.tableData.map(function (item) {
            　return item['id']; 
          });
          window.sessionStorage.setItem("ReCusIdList", this.ReCusIdList);
          //标签数字
          if (res.data.dataModel.total > 0) {
            this.$store.state.common.zfpCount = res.data.dataModel.total
          }else{
            this.$store.state.common.zfpCount = ""
          }
          // this.clearAllCheck();
          this.loading = false;
          this.$message.success("已为您找到以下客户(#^.^#)");
        }else{
          this.$message.error(res.data.messageModel.messageText);
          this.clearAllCheck();
          this.loading = false
        }
        })
      .catch(error => {
        console.log(error);
      });
    },
    changeCus (val) {
      this.customerId = []
      // console.log(val);// 返回的是选中的列的数组集合
      for (let i = 0; i < val.length; i++) {
        this.customerId.push(val[i].id); 
      }
    },
    //加入公共池
    addGGC(){
      this.disButton()
      this.loading = true;
      this.$axios
      .post(`/spider/customer/addToPool?operationId=${this.currentUser.currentid}&customerId=${this.customerId}`)
      .then(res => {
        // console.log(res);
        let messageText = res.data.messageModel.messageText;
        if (messageText == "修改成功") {
          this.$message({  message: '已将选中的客户成功添加到公共池',type: 'success'});
          this.pageConfig.currentPage = 1;
          this.getCusList();
        }else{
          this.loading = false
          this.$message.error("添加失败/(ㄒoㄒ)/~~");  
        }
      })
      .catch(error => {
        console.log(error);
      });
    },
    //将按钮禁用两秒
    disButton(){
      this.disTBN = true
      setTimeout(() => {
        this.disTBN = false
      }, 1000);
    },
    //清空所有筛选条件的方法
    clearAllCheck(){
      for (let i = 0; i < this.formLabelAlign.length; i++) {
        this.formLabelAlign[i] = "";
      }
        this.value1 = "" 	//未分割的完整版时间区间
    },
    //判断时间种类是否禁用
    hiddenTimeKind(vId){
      let obj = {};
      obj = this.kindtimeList.find(item => {
        //这里的fenselectList就是上面遍历的数据源
        return item.id === vId; //筛选出匹配数据
      });
      // console.log(obj);
      if (obj.name == "") {
        this.showTimeKind = true
      }else{
        this.showTimeKind = false
      }
    },
    //判断时间区间是否隐藏
    holderQuJian(vId){
      let obj = {};
      obj = this.timeList.find(item => {
        //这里的fenselectList就是上面遍历的数据源
        return item.id === vId; //筛选出匹配数据
      });
      // console.log(obj.name);
      if (obj.id == "customize") {
        this.isShow = true;
      }  
      else {
        this.isShow = false;
        this.value1 = ""
      }
    },
      //分页的方法
    handleSizeChange(val) {
      // console.log(val);
      if (this.pageConfig.currentPage != 1) {
        this.pageConfig.currentPage = 1;
        this.pageConfig.pageSize = val;
         this.getCusList()
      }else{
        this.pageConfig.pageSize = val;
         this.getCusList()
      }
    },
    handleCurrentChange(val) {
      // console.log(val);
        this.pageConfig.currentPage = val;
         this.getCusList()
      // }
    },
    //编辑
    handleEdit(index, row) {
      let CusId = row.id;
      let CusName = row.name;
      let addatbn = "true";
      // 编程式导航;
      // this.$router.push({ path: `/myCusEdit/${CusName}`, query: { "CusId": CusId ,"addatbn" :"true"} });
      this.$router.push({ path: `/myCusEdit`, query: { "CusId": CusId ,"addatbn" :"true"} });
      window.sessionStorage.setItem("CusId", CusId);
      window.sessionStorage.setItem("addatbn", addatbn);
      // window.sessionStorage.setItem(CusName, addatbn);
    },
    //查询
    checkCus(){
      this.disButton()
      this.pageConfig.currentPage = 1
      this.pageConfig.pageSize = 10
      if (this.value1 != "" || this.formLabelAlign.dayType == "customize") {
        this.formLabelAlign.beginTime = (this.value1)[0];
        this.formLabelAlign.endTime = (this.value1)[1];
        if (this.formLabelAlign.beginTime == this.formLabelAlign.endTime) {
          this.formLabelAlign.beginTime = this.formLabelAlign.beginTime + " " + "00:00:00";
          this.formLabelAlign.endTime = this.formLabelAlign.endTime + " " + "23:59:59";
        }
      }else{
        this.formLabelAlign.beginTime = "";
        this.formLabelAlign.endTime = "";
      }    
      this.getCusList()
    },
    // 获取未处理的数据数量
    getUnread(){
      this.disButton()
      this.$axios
      .get(`/spider/customer/getCusCount?userId=${this.currentUser.currentid}`)
      .then(res => {  
        if (res.data.messageModel.code != 0) {  
          this.$message.error(res.data.messageModel.messageText);
        }else{ 
          this.$store.commit('getUnread',res.data.dataModel);
        }
        })
      .catch(error => {
        console.log(error);
      });
    },
    //进入未处理详情页
    enterDetail(val){
      // 编程式导航
      this.$router.push({ path: '/UnhandleR', query: { "zfpSearchLevel": val } })
      window.sessionStorage.setItem("zfpSearchLevel", val);
    },
    //获取待处理客户提醒  type的值为my即为我的用户 zfp为再分配客户 team为团队客户
    getDaiChuLiNum(){
      this.$axios.get(`/spider/customer/getDCL?userId=${this.currentUser.currentid}&type=zfp`).then(res => {  
        this.daiGenJinNum = res.data.dataModel;
      })   
      .catch(error => {
        console.log(error);
      });
    },
    //获取单选的跟进时间类型
    agreeChange(val){
      // console.log(val);
      if (val == 1) {
        this.formLabelAlign.visitDayType = ""
      }else if (val == 2) {
        this.formLabelAlign.visitDayType = "yesmonth"
      }else if (val == 3) {
        this.formLabelAlign.visitDayType = "yestoday"
      }else if (val == 4) {
        this.formLabelAlign.visitDayType = "today"
      }else if (val == 5) {
        this.formLabelAlign.visitDayType = "sevenDay"
      }else if (val == 6) {
        this.formLabelAlign.visitDayType = "tomonth"
      }
    }
  },
  // 本地过滤器
  filters: {
    formatTime(value) {
      if (value == null) {
        return ""
      }
      return moment(value).format("YY-MM-DD HH:mm:ss");
      // moment(new Date().setTime(new Date().getTime() - 3600 * 1000 * 24 * 1))
    },
    getTime(value) {
      if (value == null) {
        return ""
      }
      return moment(value).valueOf();
    },
    remarksPanKong(value) {
      if (value == "null") {
        return ""
      }
      return value;
    },
    //判断星级状态
    levelKind(val) {
      // console.log(val);
      if (val == "0") {
        return  "0星"
      }else if(val == "1"){
        return  "1星"
      }else if(val == "2"){
        return  "2星"
      }else if(val == "3"){
        return "2星+"
      }else if(val == "4"){
        return  "3星"
      }else if(val == "5"){
        return "4星"
      }else{
        return ""
      }
    }
  },
  created () {
    // if (window.sessionStorage.getItem("prohibitLogin") == "true") {
      this.currentUser.currentName = window.sessionStorage.getItem("name")
      this.currentUser.currentid = window.sessionStorage.getItem("id")
      this.$axios
      .get(`/spider/customer/getAllCustomerList?searchType=true&pageSize=10&currentPage=1&userId=${this.currentUser.currentid}`)
      .then(res => {
        if (res.data.messageModel.code == 0) {
          if (res.data.dataModel.total == 0) {
            this.$message('抱歉，没有找到符合搜索条件的客户');
            this.clearAllCheck();
            this.tableData = [];
            this.pageConfig.total = 0;
            this.$store.state.common.zfpCount = "";
            this.loading = false
            return false;
          }
          //判断客户再分配时间晚于备注时间的方法开始
          let DataList = res.data.dataModel.list
          for (let i = 0; i < DataList.length; i++) {
            // console.log(DataList[i].zfpTime);console.log(DataList[i].lastNoteTime);
            if (DataList[i].zfpTime != ""&& DataList[i].lastNoteTime != "" && DataList[i].zfpTime != null&& DataList[i].lastNoteTime != null ) {
              if (moment(DataList[i].zfpTime).valueOf() > moment(DataList[i].lastNoteTime).valueOf()) {
                DataList[i].ShowStar = true;
              }else{
                DataList[i].ShowStar = false;
              }
            }
            if (DataList[i].lastNoteTime == null || DataList[i].lastNoteTime == "null") {
              DataList[i].ShowStar = true;
            }
          }
          //判断客户再分配时间晚于备注时间的方法结束
          this.$message.success("已为您找到以下客户(#^.^#)");
          this.tableData = DataList;
          this.pageConfig.total = res.data.dataModel.total;
          //将获取的再分配客户ID表存入本地
          this.ReCusIdList = this.tableData.map(function (item) {
            　return item['id']; 
          });
          window.sessionStorage.setItem("ReCusIdList", this.ReCusIdList);
          //标签数字
          if (res.data.dataModel.total > 0) {
            this.$store.state.common.zfpCount = res.data.dataModel.total
          }else{
            this.$store.state.common.zfpCount = ""
          }
          // this.clearAllCheck();
          this.loading = false
        }else{
          this.loading = false
          this.$message.error(res.data.messageModel.messageText);
          this.clearAllCheck();
          this.tableData = []
          this.pageConfig.total = 0;
        }
        })
      .catch(error => {
        console.log(error);
      });
    // }else{
    //   this.$message.warning("请先进行登录操作！");
    //   this.$router.push("login");
    // } ;
    this.getUnread()
    let component = this
    document.onkeydown = function (e) {
      var key = window.event.keyCode
      if (key === 13) {
        component.checkCus()
      }
    }
    this.getDaiChuLiNum()
  },
  activated () {
    this.getCusList()
    this.getUnread()
    this.getDaiChuLiNum()
  }
};
</script>

<style  lang='scss'>
.redistribution-container {
  // 播报文字颜色
  #unread {
    margin-top: 10px;
    margin-bottom: 15px;  
    .unread {
      font-size: 14px;
      color: #000000;
      margin-left: 22px;
    }
    .unreadNuM {
      font-size: 18px;
      color: #c73e3a;
    }
  }
  input.el-input__inner {
    width: 170px;
    height: 32px;
    padding-left: 10px;
}
//突出隔行的颜色差异
.el-table {
  font-size: 12px;
  .cell {
    padding:0 1px;
    line-height: 16px;
  }
  th {
    padding: 0;
  }
  th.is-sortable {
    .cell {
      text-align: center;
      line-height: 16px;
    }
  }
  .warning-row {
    background: #fff;
  }
   .success-row {
    background: #D3D3D3;
  }
  td {//取消单元格的上下padding
    padding: 2px 0;
    border-bottom: 1px solid rgb(211, 205, 205);
    border-right: 1px dashed #d3cdcd;
  }
   .el-button--mini{
    border: 0;
    padding: 5px 15px;
    margin: 5px 0;
    background: rgba(255,255,255,0.01);
  }
  a:hover {
    color: aqua;
  }
} 
// 时间分类框样式
 input.el-input__inner#kinds,
 /deep/input.el-input__inner#time {
    width: 85px;
    padding-left: 7px;
    height: 32px!important;
}
// 日期选择器
daterange.el-input, .el-date-editor--daterange.el-input__inner, .el-date-editor--timerange.el-input, .el-date-editor--timerange.el-input__inner {
    width: 240px;
    height: 36px;
    vertical-align: middle;
    .el-date-editor .el-range__icon {
    line-height: 27px;
    }
    .el-date-editor .el-range-separator {
    width: 5%;
}
/deep/.block,
#block {
  border: none !important;
  /deep/.el-date-editor--daterange {
    width: 240px !important; 
  }
}
}
.el-form-item {
  display: inline-block;
  margin-left: 10px;
  margin-top: 5px;
  margin-bottom: 0;
}
.el-form-item:nth-child(n + 6) {
  margin-top: 0;
}
.el-select.time {
  margin-left: 20px;
}
.el-input--suffix .el-input__inner.fanwei {
  padding-right: 30px;
  width: 30px;
}
.filterCondition {
  background-color: #fff;
  margin-bottom: 20px;
}
.check {
  margin-left: 27px;
  padding: 10px 20px;
}
.ell {
  // overflow: hidden;
  // text-overflow: ellipsis;
  // white-space: nowrap;
  word-break:normal;
  text-indent: -2em;
  margin: 0 0 0 2em;
  line-height: 1.2;
}
//分页框样式设置（避免页面被覆盖）
    .el-pagination .el-input__inner {
      width: 100px;
    }
}
</style>